let Vue;
let myForEach = (obj, callback) => {
  Object.keys(obj).forEach((key) => {
    callback(key, obj[key]);
  });
};
class Store {
  constructor(options) {
    //获取用户new实例中的参数
    console.log(options);
    this.vm = new Vue({
      data: {
        state: options.state,
      },
    });
    let getters = options.getters;

    this.getters = {};

    myForEach(getters, (getterName, value) => {
      Object.defineProperty(this.getters, getterName, {
        get: () => {
          return value(this.state);
        },
      });
    });

    let mutations = options.mutations;
    this.mutations = {};
    myForEach(mutations, (mutationName, value) => {
      this.mutations[mutationName] = (payload) => {
        //订阅
        value(this.state, payload);
      };
    });

    let actions = options.actions;
    this.actions = {};
    myForEach(actions, (actionName, value) => {
      this.actions[actionName] = (payload) => {
        value(this, payload);
      };
    });
  }
  commit = (mutationName, payload) => {
    this.mutations[mutationName](payload); //发布
  };

  dispatch = (actionName, payload) => {
    this.actions[actionName](payload);
  };

  get state() {
    return this.vm.state;
  }
}

const install = (_Vue) => {
  //vue的构造函数
  Vue = _Vue;
  Vue.mixin({
    beforeCreate() {
      if (this.$options.store) {
        this.$store = this.$options.store;
      } else {
        this.$store = this.$parent && this.$parent.$store;
      }
    },
  });
};

export default {
  Store,
  install,
};
